package com.ebupt.migu.music.global.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ebupt.migu.globalpopup.entity.ActivityInfo;
import com.ebupt.migu.globalpopup.entity.DappChameleonEffectDataD;
import com.ebupt.migu.globalpopup.entity.PopupInfo;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.global.mapper.ActivityInfoMapper;
import com.ebupt.migu.music.global.mapper.DappChameleonEffectDataDMapper;
import com.ebupt.migu.music.global.mapper.PopupInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author tz
 */
@EnableScheduling
@Component
@Slf4j
public class EffectTask {

    @Resource
    private ActivityInfoMapper activityInfoMapper;
    @Resource
    private PopupInfoMapper popupInfoMapper;
    @Resource
    private DappChameleonEffectDataDMapper dappChameleonEffectDataDMapper;

    /**
     * 根据效果统计更改多文案默认配置
     */
    @Async
    @Scheduled(cron = "${cron.default_by_effect}")
    public void defaultByEffect() {
        log.info("定时任务开始 ----> 根据效果统计更改多文案默认配置");
        List<PopupInfo> popupInfos = popupInfoMapper.selectList(new QueryWrapper<PopupInfo>().lambda().select());
        //按活动id分组
        Map<String, List<PopupInfo>> collect = popupInfos.stream().collect(Collectors.groupingBy(PopupInfo::getActivityId));
        collect.forEach((key, value) -> {
            //多文案时
            if (value.size() > 1) {
                // 当所有文案都没有设置过默认值
                if (value.stream().noneMatch(e -> e.getIsDefault().equals(1))) {
                    // 获取对应的效果统计和验证测试天数
                    ActivityInfo activityInfo = activityInfoMapper.selectOne(new QueryWrapper<ActivityInfo>().lambda()
                            .eq(ActivityInfo::getActivityId, key));
                    List<DappChameleonEffectDataD> ds = dappChameleonEffectDataDMapper.selectList(new QueryWrapper<DappChameleonEffectDataD>().lambda()
                            .eq(DappChameleonEffectDataD::getActivityId, key));
                    Optional<Long> max = ds.stream().collect(Collectors.groupingBy(DappChameleonEffectDataD::getActivityCid, Collectors.counting()))
                            .values().stream().max(Long::compareTo);
                    // 满足测试天数等于效果统计天数时，没有效果统计记录天数为0
                    if (activityInfo.getTestDay().equals(max.orElse(0L).intValue())) {
                        //根据最新日期的
                        String yesterday = DateUtil.parseDateToStr(DateUtil.getYesterday(), DateUtil.DATE_FORMAT_YYYYMMDD);
                        List<DappChameleonEffectDataD> list = ds.stream().collect(Collectors.groupingBy(DappChameleonEffectDataD::getDealDay)).get(yesterday);
                        Optional.ofNullable(list).ifPresent(ls -> {
                            // 累计点击人数/累计曝光人数
                            Optional<DappChameleonEffectDataD> reduce = ls.stream().reduce((x1, x2) -> {
                                if (x1.getClickCntsM() / x1.getExposureCntsM() > x2.getClickCntsM() / x2.getExposureCntsM()) {
                                    return x1;
                                } else {
                                    if (x1.getClickCntsM() / x1.getExposureCntsM() - x2.getClickCntsM() / x2.getExposureCntsM() == 0) {
                                        // 累计点击人数/累计曝光人数 相同时，取累计点击人数较大的
                                        return x1.getClickCntsM() > x2.getClickCntsM() ? x1 : x2;
                                    } else {
                                        return x2;
                                    }
                                }
                            });
                            // 效果统计最优子文案,设置默认的子文案
                            reduce.ifPresent(e -> {
                                log.info("验证测试{}天,设置{}为默认文案", activityInfo.getTestDay(), e.getActivityCid());
                                popupInfoMapper.update(null,new UpdateWrapper<PopupInfo>().lambda()
                                        .eq(PopupInfo::getActivityCid,e.getActivityCid())
                                        .set(PopupInfo::getIsDefault,1));
                            });
                        });
                    }
                }
            } else {
                // 单文案时,没有默认的设置默认值
                if (!value.get(0).getIsDefault().equals(1)) {
                    popupInfoMapper.update(null,new UpdateWrapper<PopupInfo>().lambda()
                    .eq(PopupInfo::getActivityId,key)
                    .set(PopupInfo::getActivityCid,key.concat("_0"))
                    .set(PopupInfo::getIsDefault,1));
                }
            }
        });
        log.info("定时任务结束 ----> 根据效果统计更改多文案默认配置");
    }
}
